package org.edu.modules.dorm.controller;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.edu.common.api.vo.Result;
import org.edu.common.util.oss.OssBootUtil;
import org.edu.modules.dorm.constant.OssDownloadUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Api(tags="图片")
@RestController
@RequestMapping("dorm/image")
public class OssDormController {

  @ApiOperation(value="图片上传", notes="图片上传")
  @RequestMapping(value = "/impotrColl", method = RequestMethod.POST)
  @ResponseBody
  public Result<Object> impotrColl(@RequestParam MultipartFile file) throws Exception {
//      Date d = new Date();
////      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
////      String dateNowStr = sdf.format(d);
////
////      //定义上传的文件存储位置
////      String path = "dorm/" + dateNowStr + "/" + file.getOriginalFilename();
////      String s = OssBootUtil.upload(file.getInputStream(), path);
////      return  Result.OK(s);
      File document = null;
      //获取文件名
      String fileName = file.getOriginalFilename();
      //用点来切割获取文件类型注意//.需要加双斜杠正则表达式
      String[] arr = fileName.split("\\.");
      //获取文件后缀名
      String suffixName = arr[arr.length - 1];
      if (!suffixName.equalsIgnoreCase("jpg") && !suffixName.equalsIgnoreCase("png")) {
          return Result.error(400, "文件类型不能上传");
      }
      try {
          String originalFilename = file.getOriginalFilename();
          String[] filename = originalFilename.split("\\.");
          document = File.createTempFile(filename[0], filename[1]);
          file.transferTo(document);
          document.deleteOnExit();
      } catch (IOException e) {
          e.printStackTrace();
      }
      String docName = UUID.randomUUID().toString();
      //上传文件到指定的存储空间  第一个参数 bucketName  第二个参数 OSS存储路径  第三个参数 要上传的文件
      OSSClient ossClient = new OSSClient("oss-cn-beijing.aliyuncs.com","LTAI5tPnLGtPS6r8BpncZMrm","BAJbUlVLXD6or53Zcw1nC8uI87UpOs");
      PutObjectResult result = ossClient.putObject("exaplebucket-beijing",docName+"/"+ fileName, document);
      ossClient.shutdown();
      return Result.OK("https://exaplebucket-beijing.oss-cn-beijing.aliyuncs.com/"+docName+"/"+fileName);
  }

  @ApiOperation(value="获取URL", notes="获取URL")
  @RequestMapping(value = "/getUrl", method = RequestMethod.POST)
  @ResponseBody
  public  String getUrl() {
      //设置过期时间
      Date expiration = new Date(new Date().getTime() + 3600L * 1000 * 24 * 365 * 10);
      //下载文件的绝对路径
      String name = "dorm/2021-03-15/ChMlWV67WcGIFt1JAF8SUWkx1I8AAPEtQMRJ7AAXxJp979.jpg";
      //返回URL，直接用URL就可以下载
      return OssBootUtil.getObjectURL(OssBootUtil.getBucketName(), name, expiration);
  }

}
